import { postRequest } from "request";
import { util, BaseErr } from "utils";
import DingInfo from "../config";
import crypto from "node:crypto";

function createContent(err: BaseErr | string) {
    let errStr = typeof err === "string" ? err : err.resMaker().errMsg;
    let content = [`### ${DingInfo.pushMessage.title}`, errStr];
    return content.join("\r\n");
}
// 钉钉推送
async function toDingDingPush(content: string, atMobiles: string[]) {
    // 签名
    let timestamp = Date.now();
    let stringToSign = `${timestamp}\n${DingInfo.dingDingSecret}`;
    const hmac = crypto.createHmac("sha256", DingInfo.dingDingSecret);
    hmac.update(stringToSign);
    const signature = hmac.digest("base64");

    // 发送
    let url = `${DingInfo.dingDingHook}&timestamp=${timestamp}&sign=${signature}`;
    let [pushErr, pushData] = await postRequest(url)(
        {
            at: {
                isAtAll: false,
                atMobiles,
            },
            markdown: {
                title: DingInfo.pushMessage.title,
                text: content,
            },
            msgtype: "markdown",
        },
        { contentType: "json" }
    );
    if (!util.nilValue(pushErr)) {
        console.log("qw发送失败", pushErr);
        return [pushErr, undefined];
    }
    console.log("发送成功");
    return [undefined, pushData];
}

// 企微 push
async function toQWPush(content: string) {
    let [err, data] = await postRequest(DingInfo.qwHook)(
        {
            msgtype: "markdown",
            markdown: {
                content,
            },
        },
        { contentType: "json" }
    );
    if (!util.nilValue(err)) {
        console.log("qw发送失败", err);
        return [err, undefined];
    }
    console.log("发送成功");
    return [undefined, data];
}

export { toQWPush, createContent, toDingDingPush };
